<?php
if( !defined('IN_INDEX') )
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}
if(!checkSession())
{
			function redirect($url)
			{
			?>
				<script type="text/javascript">
					{
					window.location = "<?=$url?>";
					}
				</script>
			<?php 
			}
			redirect("index.php?action=login");
	exit;
}

// Upload profile picture
if(isset($_POST['submit_upload']))
{
	//Get file attributes
	$name = $_FILES['profilepic']['name'];
	$size = $_FILES['profilepic']['size'];
	$tmp_name = $_FILES['profilepic']['tmp_name'];
	
	if(substr($name, strpos($name, '.') + 1) == "JPG" || substr($name, strpos($name, '.') + 1) == "jpg" || substr($name, strpos($name, '.') + 1) == "jpeg" || substr($name, strpos($name, '.') + 1) == "JPEG")
	{
	
				
				// Start upload process
				$location = "user_data/".$USER->getId()."/$name";
				$location_thumbl = "user_data/".$USER->getId()."/thumbl_$name";
				$location_thumbs = "user_data/".$USER->getId()."/thumbs_$name";
				
				//Make upload folder if it dont exists
				$dirname = $USER->getId();  
				$filename = "user_data/". $dirname . "/";  
		   
				if(file_exists($filename)) 
				{   
				} 
				else 
				{  
					mkdir("user_data/".$USER->getId()."", 0777);
				}
				
				// Move picture to folder
				move_uploaded_file($tmp_name, $location);
				
				//Image resizer
				class ImgResizer {
				private $originalFile = '';
				public function __construct($originalFile = '') {
					$this -> originalFile = $originalFile;
				}
				public function resize($newWidth, $targetFile) {
					if (empty($newWidth) || empty($targetFile)) {
						return false;
					}
					$src = imagecreatefromjpeg($this -> originalFile);
					list($width, $height) = getimagesize($this -> originalFile);
					$newHeight = ($height / $width) * $newWidth;
					$tmp = imagecreatetruecolor($newWidth, $newHeight);
					imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
					if (file_exists($targetFile)) {
						unlink($targetFile);
					}
					imagejpeg($tmp, $targetFile, 85); // between 0 – 100 for output image quality with 100 being the most luxurious
					}
				}
				
				// Resizing two smaller thumbnails
				$work = new ImgResizer("".$location.""); 
				$work -> resize(150, "".$location_thumbl.""); // (150x?).
				$work -> resize(70, "".$location_thumbs.""); //  (70x?).
				
				//Update the users avatarpath
				updateAvatarPath($name, $USER->getId());
		
				echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
				<center><meta http-equiv=\"refresh\"content=\"3;url=index.php?action=profile&sub=edit_personal\">";
				echo "<br/><h2>" . ucfirst(translate('picture_uploaded')) . "</h2>\n";
				echo "<br/><br />" . translate('redirectedin'). " <a href=\"index.php?action=profile&sub=edit_personal\">" . translate('clickhere') . "</a>.</center><div class='fixed'>
							</div>
						</div>
						</div>
					<div class='fixed'>
					</div>
					<div id='footer'>
					<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
						<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
						</div>";
				exit;
				}
				else
				{
				echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
					<center><meta http-equiv=\"refresh\"content=\"3;url=index.php?action=profile&sub=edit_personal\">";
					echo "<br/><h2>" . ucfirst(translate('please_select_picture')) . "</h2>\n";
					echo "<br/><br />" . translate('redirectedin'). " <a href=\"index.php?action=profile&sub=edit_personal\">" . translate('clickhere') . "</a>.</center><div class='fixed'>
								</div>
							</div>
							</div>
						<div class='fixed'>
						</div>
						<div id='footer'>
						<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
							<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
							</div>";
					exit;
		}
}

$reg['firstname']=$USER->getFirstname();
$reg['lastname']=$USER->getLastname();
$reg['email']=$USER->getEmail();
//$reg['password']="";
$reg['country']=$USER->getCountry();
$birthday = $USER->getBirthday();
$bd = explode('-',$birthday) ;
$reg['about']=$USER->getAbout();

$reg['day']=$bd[0];
$reg['month']=$bd[1];
$reg['year']=$bd[2];
$reg['conf_pass'] = "";

$GENDER_LIST = array('male', 'female');
$COUNTRY_LIST  = get_country_list();
$preselected_country = $reg['country'];

$missing = array();
$output ="";
if(isset($_POST['reg_submit']))
{
	$reg_checked = 0;
	$cur_email = $USER->getEmail();
	$reg['firstname']=$_POST['reg_firstname'];
	$reg['lastname']=$_POST['reg_lastname'];
	$reg['email']=$_POST['reg_email'];
	//$reg['password']=$_POST['reg_pass'];
	$reg['country']=$_POST['country_list'];
	$reg['day']=$_POST['reg_bday_day'];
	$reg['month']=$_POST['reg_bday_month'];
	$reg['year']=$_POST['reg_bday_year'];
	$reg['conf_pass']=$_POST['conf_pass'];
	$reg['about']=$_POST['reg_about'];
	
	if($reg['country'] != "")
	{
		$preselected_country = $reg['country'];
	}
	foreach($reg as $k => $v)
	{
		//echo $k . " | " . $v . "<br />\n";
		
		if(isset($v) && $v != "")
		{
			if($k == "email")
			{
				if(strstr($v, '@') && strstr($v, '.'))
				{
					if($cur_email != $v)
					{
						if(checkUserExistance('email', $v))
						{
							$missing['email'] = "is_regged";
						}
						else
						{
							$reg_checked++;
						}
					}
					else
					{
						$reg_checked++;
					}
				}
				else
				{
					$missing['email'] = "not_email";
				}
			}
			else if($k == "conf_pass")
			{
				if($USER->checkPassword(cryptString($v)))
				{
					$reg_checked++;
				}
				else
				{
					$missing['conf_pass'] = "missmatch_password";
				}
			}
			else
			{
				$reg_checked++;
			}
		}
		else
		{
			$missing[$k] = "missing";
		}
	}
	
	
	if($reg_checked >= 9)
	{
		$new_pass = "";
		if($_POST['reg_pass'] != "")
		{
			$new_pass = "user_password='" . cryptString($_POST['reg_pass']) . "', ";
		}
		$birthday = $reg['day'] . "-" . $reg['month'] . "-" . $reg['year'];
		
		$sql = "UPDATE " . USERS_TABLE . " SET ".
		"user_email='" . $reg['email'] . "', ".
		$new_pass .
		"user_birthday='" . $birthday . "', ".
		"user_country='" . $reg['country'] . "', ".
		"user_about='" . $reg['about'] . "', ".
		"user_firstname='" . $reg['firstname'] . "', ".
		"user_lastname='" . $reg['lastname'] . "' ".
		"WHERE user_id='" . $USER->getId() . "'";
		if(!$result = $db->sql_query($sql))
		{
			printerror("SQL ERROR", mysql_error() ."<br />" . mysql_errno());
		}
		else
		{
		echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
		<center><meta http-equiv=\"refresh\"content=\"3;url=index.php?action=profile&sub=edit_personal\">";
		echo "<h2>" . ucfirst(translate('settings_saved')) . "</h2>\n";
		echo "<br/>" . translate('redirectedin'). " <a href=\"index.php?action=profile&sub=edit_personal\">" . translate('clickhere') . "</a>.</center>
		<div class='fixed'>
					</div>
				</div>
				</div>
			<div class='fixed'>
			</div>
			<div id='footer'>
			<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
				<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
                </div>";
		}
		exit;
	}
}

// Remove profil picture
if(isset($_POST['delete_picture_submit']))
{
	// Blank out the user_AvatarPath
	removeProfilePic($USER->getId());
	
	// Delete picture from server
	$filepath = "user_data/".$USER->getId() ."/" . $USER->getAvatarpath() ."";
	$filepath_thumbl = "user_data/".$USER->getId() ."/thumbl_" . $USER->getAvatarpath() ."";
	$filepath_thumbs = "user_data/".$USER->getId() ."/thumbs_" . $USER->getAvatarpath() ."";
	unlink($filepath);
	unlink($filepath_thumbl);
	unlink($filepath_thumbs);
	
	echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
				<center><meta http-equiv=\"refresh\"content=\"3;url=index.php?action=profile&sub=edit_personal\">";
				echo "<br/><h2>" . ucfirst(translate('picture_removed')) . "</h2>\n";
				echo "<br/><br />" . translate('redirectedin'). " <a href=\"index.php?action=profile&sub=edit_personal\">" . translate('clickhere') . "</a>.</center>
				<div class='fixed'>
					</div>
				</div>
				</div>
			<div class='fixed'>
			</div>
			<div id='footer'>
			<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
				<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
                </div>";
				exit;
}

//Delete the user from the system
	if(isset($_POST['delete_submit']))
		{
			//Delete the user
		   deleteUser($USER->getId());
		   //Delete all comments from the user
		   deleteAllCommentByUserId($USER->getId());
		   //Delete all commets in blog
		   deleteAllCommentsInBlog($USER->getId());
		   //Delete all lift from the user
		   deleteAllLiftsFromUser($USER->getId());
		   //Delete all the trainings from the user
		   deleteAllTrainingsByUserId($USER->getId());
		   //Delete all friendconnections to user
		   deleteAllFriendsByUserId($USER->getId());
		   
				echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
				<center><meta http-equiv=\"refresh\"content=\"3;url=index.php?logout\">";
				echo "<br/><h2>" . ucfirst(translate('user_deleted')) . "</h2>\n";
				echo "<br/>" . translate('welcome_back');
				echo "<br/><br />" . translate('redirectedin'). " <a href=\"index.php?logout\">" . translate('clickhere') . "</a>.</center>
				<div class='fixed'>
					</div>
				</div>
				</div>
			<div class='fixed'>
			</div>
			<div id='footer'>
			<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
				<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
                </div>";
				exit;
		}
?>
<script src="./jscript/prettyphoto/js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="./jscript/prettyphoto/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="./jscript/prettyphoto/js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
<div id='postpath'>
	<a title="<?php echo translate('gotofrontpage'); ?>" href="index.php"><?php echo translate('home'); ?></a>
    &gt; <a href="index.php?action=blogs" title='<?php echo translate('showallblogs'); ?>'><?php echo translate('blog'); ?></a> 
    &gt; <a href="index.php?action=profile&id=<?php echo $USER->getId(); ?>"><?php echo ucf($USER->getFirstname()) . " " . ucf($USER->getLastname()); ?></a>
	&gt; <a href="index.php?action=profile&amp;sub=edit" title='<?php echo translate('edit'); ?>'><?php echo translate('edit'); ?></a> 
	&gt; <a href="index.php?action=profile&amp;sub=edit_personal" title='<?php echo translate('personalsettings'); ?>'><?php echo translate('personalsettings'); ?></a> 
</div>
<br />

<h2> <img src="img/people.png" /> <?php echo translate('personalsettings'); ?></h2>
<br />
<?php echo translate('changeyourpersonalsettings'); ?>.
<br />
<br />
<form method="post" action="index.php?action=profile&amp;sub=edit_personal" />
<table>
<td>
	<table class="reg_table" border="0" cellspacing="0">
        <tr><td colspan="2" style="background-color: #F2F2F2; font-size:14px; padding: 5px;"><b><?php echo translate('accountinformation'); ?></b></td></tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
    	<tr>
        	<td class="reg_label"><?php echo ucfirst(translate('firstname')); ?>: </td>
            <td><input type="text" class="inputtext" size="25" id="reg_firstname" name="reg_firstname" value="<?php echo $reg['firstname']; ?>" />
				<?php 
                if(isset($missing['firstname'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['firstname']) . "</span>";
                }
                ?>
            </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        <tr>
        	<td class="reg_label"><?php echo ucfirst(translate('lastname')); ?>: </td>
            <td><input type="text" class="inputtext" size="25" id="reg_lastname" name="reg_lastname" value="<?php echo $reg['lastname']; ?>" />
				<?php 
                if(isset($missing['lastname'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['lastname']) . "</span>";
                }
                ?>
            </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        <tr>
        	<td class="reg_label"><?php echo ucfirst(translate('country')); ?>: </td>
            <td><?php include('inc/country_select.php'); ?>
            	<?php 
                if(isset($missing['country'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['country']) . "</span>";
                }
                ?>
          </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        <tr>
        	<td class="reg_label"><?php echo ucfirst(translate('gender')); ?>: </td>
            <td>
            	<?php echo ucfirst(translate($USER->getGender())); ?>
            </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        <tr>
        	<td class="reg_label"><?php echo ucfirst(translate('birthday')); ?>: </td>
            <td>
            	<select class="select" id="reg_bday_day" name="reg_bday_day">
                	<option value=""><?php echo ucfirst(translate('day')); ?></option>
					<?php
					for($i=1; $i<=31; $i++)
					{
						if($i == $reg['day'])
						{
							echo "<option value=\"" . $i . "\" selected=\"selected\">" . $i . "</option>\n";
						}
						else
						{
							echo "<option value=\"" . $i . "\">" . $i . "</option>\n";
						}
					}
					?>
            	</select>
                <select class="select" id="reg_bday_month" name="reg_bday_month">
               	  <option value=""><?php echo ucfirst(translate('month')); ?></option>
					<?php
					foreach($MONTHS as $k => $v)
					{
						if(($k+1) == $reg['month'])
						{
							echo "<option value=\"" . ($k+1) . "\" selected=\"selected\">" . ucfirst(translate($v)) . "</option>\n";
						}
						else
						{
							echo "<option value=\"" . ($k+1) . "\">" . ucfirst(translate($v)) . "</option>\n";
						}
					}
					?>
           	  </select>
                <select class="select" id="reg_bday_year" name="reg_bday_year">
               	  <option value=""><?php echo ucfirst(translate('year')); ?></option>
                    <?php
					for($i=date('Y', time()); $i>=1900; $i--)
					{
						if($i == $reg['year'])
						{
							echo "<option value=\"" . $i . "\" selected=\"selected\">" . $i . "</option>\n";
						}
						else
						{
							echo "<option value=\"" . $i . "\">" . $i . "</option>\n";
						}
					}
					?>
           	  </select>
                <?php 
				if(isset($missing['day']) or isset($missing['month']) or isset($missing['year']))
				{
					echo "<span class=\"error\"><-- " . translate('missing') . "</span>";
				}
                ?>
          </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        
        <tr>
        <td colspan="2" style="background-color: #F2F2F2; font-size:14px; padding: 5px;"><b><?php echo translate('about_me'); ?></b></td></tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
    	<tr>
        	
         <td colspan="2">
         <textarea rows="4" cols="56" id="reg_about" name="reg_about" ><?php echo $reg['about']; ?></textarea>
         <?php 
                if(isset($missing['about'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['about']) . "</span>";
                }
                ?>
         </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        
        <td colspan="2" style="background-color: #F2F2F2; font-size:14px; padding: 5px;"><b><?php echo translate('logininformation'); ?></b></td></tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
    	<tr>
        	<td class="reg_label"><?php echo ucfirst(translate('email')); ?>: </td>
           <td><input type="text" class="inputtext" size="25" id="reg_email" name="reg_email" value="<?php echo $reg['email']; ?>" />
            	<?php 
                if(isset($missing['email'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['email']) . "</span>";
                }
                ?>
            </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>
        <tr>
        	<td class="reg_label"><?php echo ucfirst(translate('password')); ?>: </td>
            <td><input type="password" class="inputtext" size="25" id="reg_pass" name="reg_pass" value="" />
            	<?php 
                if(isset($missing['password'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['password']) . "</span>";
                }
                ?>
            </td>
        </tr>
        <tr>
        	<td>&nbsp;</td>
        </tr>        
        <tr>
        <td colspan="2" style="background-color: #F2F2F2; font-size:14px; padding: 5px;"><b><?php echo translate('confirm'); ?></b></td>
        </tr>
         <tr>
        	<td>&nbsp;</td>
        </tr>
        <tr>
        	<td>
	        	<?php echo translate('currentpassword'); ?>:</td> <td><input type="password" class="inputtext" id="conf_pass" size="25" name="conf_pass" value="" />
	        	<?php 
						if(isset($missing['conf_pass'])) 
            {
                echo "<span class=\"error\"><-- " . translate($missing['conf_pass']) . "</span>";
            }
            ?>
          </td>
        </tr>
        
  		<tr>
        	<td>&nbsp;</td>
        </tr>
        
        <tr>
        <td align="right">
  <input style="font-weight:bold;" type="submit" id="reg_submit" name="reg_submit" value=" <?php echo ucfirst(translate('save')); ?> " /></form>
</td>
        <td align="left">
        <form method="post" onsubmit="if(!confirm('<?php echo translate('deletewarning2'); ?>'))return false;" action="index.php?action=profile&amp;sub=edit_personal" />
<input type="submit" style="font-weight:bold; color:#F00;" id="delete_submit" name="delete_submit" value=" <?php echo translate('deletemyaccount'); ?> " />
</form>
		</td>
        </tr>
	</table>
</td>
<td valign="top" style="padding-left:100px;">
<center>
<h1><?php echo translate('profilepic'); ?></h1>
<br />
<?php
		if($USER->getAvatarpath() != "")
		{
			$profile_pic_path = $CONFIG['user_data_path'] . $USER->getId() . "/thumbl_" . $USER->getAvatarpath();
			$profile_pic_pathfull = $CONFIG['user_data_path'] . $USER->getId() . "/" . $USER->getAvatarpath();
			if(file_exists($profile_pic_path))
			{
				echo "<a href='". $profile_pic_pathfull ."' rel='prettyPhoto'><img src=\"" . $profile_pic_path . "\" alt=\"" . translate('profile_picture') . "\" class=\"profile_picture\" /></a>\n";
			}
			else
			{
				echo $profile_pic_path;
			}
		}
		else
		{
			if($USER->getGender() == "female")
			{
				echo "<img src=\"" . $CONFIG['user_data_path'] . "profile_female.gif\" alt=\"" . translate('profile_picture') . "\" class=\"profile_picture\" />\n";
			}
			else
			{
				echo "<img src=\"" . $CONFIG['user_data_path'] . "profile_male.gif\" alt=\"" . translate('profile_picture') . "\" class=\"profile_picture\" />\n";
			}
		}
		?>
        <br /><br />
        <b><?php echo translate('supported_file_types'); ?>:</b> .jpg - .jpeg
        <br /><br />
<form enctype="multipart/form-data" method="post" action="index.php?action=profile&amp;sub=edit_personal" />
	<input style="font-weight:bold;" type="file" size="12" name="profilepic" />
	<input type="submit" style="font-weight:bold;" name="submit_upload"  value=" <?php echo ucfirst(translate('uploadpic')); ?> " />
  </form>
  <?php 
  
  if($USER->getAvatarpath() != "")
  {
  ?>
<br />
  <form method="post" onsubmit="if(!confirm('<?php echo translate('deletewarning2'); ?>'))return false;" action="index.php?action=profile&amp;sub=edit_personal" />
<input type="submit" style="font-weight:bold; color:#F00;" id="delete_picture_submit" name="delete_picture_submit" value=" <?php echo translate('remove_picture'); ?> " />
</form>
	<?php 
  }
  else
  {}
  ?>
  </center>
</td>
</table>
</b>
<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $("a[rel^='prettyPhoto']").prettyPhoto();
  });
</script>